package com.leon.util.encryption;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密类, 演示在Java中如何使用MD5进行加密 
 * @author leon.yi(linyun0528@gmail.com)
 * @since 2010-12-21
 */
public class EncryptMD5 {
	/**
	 * 32位MD5码
	 * @param source 原字符串
	 * @return 32位MD5加密码
	 * @author leon.yi(linyun0528@gmail.com)
	 * @since 2010-12-21
	 */
	public static String EncodeByMD5W32(String source) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			
			return toHexString(md5.digest(source.getBytes("utf-8")));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 16位MD5码实际上是将32位MD5码去掉前8位和后8位后的码
	 * @param source 原字符串
	 * @return 16位MD5加密码
	 * @author leon.yi(linyun0528@gmail.com)
	 * @since 2010-12-21
	 */
	public static String EncodeByMD5W16(String source) {
		String md5w32 = EncodeByMD5W32(source);
		if(md5w32 == null)
			return null;
		else {
			return md5w32.substring(8, 24);
		}
	}
	

	/**
	 * 将byte数组转换为16进制字符串
	 * @param bs byte数组
	 * @return 16进制字符串
	 * @author leon.yi(linyun0528@gmail.com)
	 * @since 2010-12-21
	 */
	public static String toHexString(byte[] bs) {
		StringBuilder sb = new StringBuilder();
		for (byte b : bs) {
			String hex = Integer.toHexString(b & 0XFF);
			if(hex.length() == 1) hex = "0" + hex;
			sb.append(hex);
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		String str = "123456";
		System.out.println(EncodeByMD5W32(str));
		System.out.println(EncodeByMD5W16(str));
	}
}